
#include "sprite.h"
#include "WeShaderProg.h"
#include "WeMatrix4.h"
#include "WeImage.h"


using namespace WackiEngine;


Sprite::Sprite(const String& img)
{
	Image image;
	image.load("../../resources/images/" + img);
	_texture.image(0, GL_RGBA, image.width(), image.height(), image.srcDataFormat(), image.srcDataType(), image.data());
	_texture.setMinFilter(GL_NEAREST);
	_texture.setMagFilter(GL_NEAREST);
}

void Sprite::setPos(const Vector2f& pos)
{
	_pos = pos;
}

void Sprite::setDir(const Vector2f& dir)
{
	_dir = dir;
}

void Sprite::render()
{
	static bool init = false;
	static ShaderProg shader("../../resources/shaders/default.vert", "../../resources/shaders/default.frag");
	static Matrix4f	mvp;
	static Matrix4f proj;
	static Matrix4f modelView;
	static GLuint pos, texcoord;

	if(!init)
	{
		proj.ortho(0, 1280, 0, 800, -1, 1);
		init = true;

		Vector<Vector3f>	verts;
		Vector<Vector2f>	texcoords;

		// top, the ships forward vector is +Y
		verts.push_back(Vector3f(-0.5f, -0.5f, 0.0f));
		verts.push_back(Vector3f(0.5f, -0.5f, 0.0f));
		verts.push_back(Vector3f(-0.5f, 0.5f, 0.0f));
		verts.push_back(Vector3f(0.5f, 0.5f, 0.0f));

		texcoords.push_back(Vector2f(0.0f, 0.0f));
		texcoords.push_back(Vector2f(1.0f, 0.0f));
		texcoords.push_back(Vector2f(0.0f, 1.0f));
		texcoords.push_back(Vector2f(1.0f, 1.0f));

		glGenBuffers(1, &pos);
		glBindBuffer(GL_ARRAY_BUFFER, pos);
		glBufferData(GL_ARRAY_BUFFER, verts.size() * sizeof(Vector3f), &verts[0], GL_STATIC_DRAW);

		glGenBuffers(1, &texcoord);
		glBindBuffer(GL_ARRAY_BUFFER, texcoord);
		glBufferData(GL_ARRAY_BUFFER, texcoords.size() * sizeof(Vector2f), &texcoords[0], GL_STATIC_DRAW);


	}

	shader.beginUse();

	modelView.identity();
	modelView.scale((float)_texture.width(), (float)_texture.height(), 1);

	Vector3f perp;
	perp = Vector3f(0.0f, 0.0f, 1.0f).cross(Vector3f(_dir));

	Matrix4f rot(
		-perp.x, -perp.y, 0.0f, _pos.x,
		-_dir.x, -_dir.y, 0.0f, _pos.y,
		0.0f, 0.0f, 1.0f, 0.0f,
		0.0f, 0.0f, 0.0f, 1.0f);

	modelView = rot * modelView;



	glActiveTexture(GL_TEXTURE0 + _texture.handle());
	_texture.bind();

	mvp = proj * modelView;
	shader.uniformMatrix4fv("mvp", 1, mvp.m(), true);
	shader.uniform1i("texture", _texture.handle());

	glBindBuffer(GL_ARRAY_BUFFER, pos);
	glEnableVertexAttribArray(0);
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);

	glBindBuffer(GL_ARRAY_BUFFER, texcoord);
	glEnableVertexAttribArray(1);
	glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0);


	glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

	glDisableVertexAttribArray(0);
	glDisableVertexAttribArray(1);

	shader.endUse();

}